<template>
  <t-skeleton :loading="loading">
  <t-collapse v-if="engineeringNodeTree.length>0">
    <template  v-for="(firstLevel, index) in engineeringNodeTree" :key="firstLevel.id">
    <t-collapse-panel :header="firstLevel.stageName">
      <!-- 第一层内容 -->
      <template #headerRightContent>
        <t-link 
          theme="primary"
          v-permission="['system:engineering-stage:engineering-stage-picture-examine']"
          v-if="hasItemsNeedingApproval(firstLevel.children)" 
          @click="handleOpenArrayDialog('update', firstLevel.children)"
        >
          审核
        </t-link> 
      </template>


      <!-- 第二层 -->
      <t-collapse >
        <template v-for="secondLevel in firstLevel.children" :key="secondLevel.id">

   
        <t-collapse-panel :header="secondLevel.stageName">
          

          <!-- 第三层 -->
          <t-collapse 
            >
            <template v-for="thirdLevel in secondLevel.children" :key="thirdLevel.id" >

            
            <t-collapse-panel >
              <template #header>
                {{ thirdLevel.stageName }}
                <t-tag style="margin-left: 10px;" :theme="getTagThemeAndLabel(thirdLevel.imgApprovalStatus - 1).theme">{{
          getTagThemeAndLabel(thirdLevel.imgApprovalStatus - 1).label
        }}</t-tag>
              </template>
              <template #headerRightContent>
                <t-space size="medium" class="flex">
                  <div v-if="thirdLevel.completeStatus === '1'">上传日期：{{JSON.parse(thirdLevel.fileUrl)[0].uploadTime }}</div>
                    
                </t-space>
              </template>
              <div>
                <image-viewer v-if="thirdLevel.uploadStatus==='1'&&JSON.parse(thirdLevel.fileUrl)" :images="(JSON.parse(thirdLevel.fileUrl)||[]).map((f: Record<string, string>) => f.url)" width="80px" height="80px" />
              </div>
                <t-button 
                  theme="primary" 
                  v-permission="['system:engineering-stage:re-upload-engineering-stage-picture']"
                  @click="handleOpenDialog('update' ,{
                    engineeringId:engineeringId,
                    id:thirdLevel.id,
                    level:thirdLevel.level,
                    parentId:thirdLevel.parentId,
                    sort:thirdLevel.sort,
                    stageName:thirdLevel.stageName,
                    fileUrl:[]
                  })" 
                  v-if="thirdLevel.imgApprovalStatus=='3'"
                >重新上传</t-button>
              </t-collapse-panel>
            </template>
          </t-collapse>
        </t-collapse-panel>
          </template>
      </t-collapse>
    </t-collapse-panel>
        </template>
  </t-collapse>
  <t-empty v-else style="margin: 100px"/>
  </t-skeleton>
    <!-- 自定义对话框 -->
  <custom-array-dialog 
    ref="customArrayDialogRef" 
    v-slot="{ formData }" 
    :api-map="{update: engineeringStagePictureExamine}" 
    header="审核"
    :on-before-save-data="handleDialogSaveData" 
    @request-success="handleDialogRequestSuccess"
    width="40%"
    >
     <!-- 第二层 -->
      <t-collapse defaultExpandAll>
        <template v-for="(secondLevel,jIndex) in formData" :key="secondLevel.id">
        <t-collapse-panel :header="secondLevel.stageName">
          <!-- 第三层 -->
          <t-collapse defaultExpandAll>
            <template v-for="(thirdLevel,index) in secondLevel.children" :key="thirdLevel.id" >
            <t-collapse-panel :header="thirdLevel.stageName">
              <template #headerRightContent>
                <t-space size="medium" class="flex">
                  <div v-if="thirdLevel.completeStatus === '1'">上传日期：{{JSON.parse(thirdLevel.fileUrl)[0].uploadTime }}</div>
                    
                </t-space>
              </template>
              <image-viewer v-if="thirdLevel.uploadStatus==='1'&&JSON.parse(thirdLevel.fileUrl)" :images="(JSON.parse(thirdLevel.fileUrl)||[]).map((f: Record<string, string>) => f.url)" width="80px" height="80px" />
                <t-form-item label="" label-width="0"  :name="`[${jIndex}].children[${index}].result`"  :rules="[{ required: true, message: '请选择' }]" >
                 
                         <t-radio-group v-model="formData[jIndex].children[index].result">
                          <t-radio
                            v-for="_ in [{label:'同意',value:'2'},{label:'驳回',value:'3'}]"
                            :key="_.value"
                            :value="_.value"
                          >
                            {{ _.label }}
                          </t-radio>
                        </t-radio-group>
                </t-form-item>
            </t-collapse-panel>
            </template>
          </t-collapse>
        </t-collapse-panel>
          </template>
      </t-collapse>
  </custom-array-dialog>
   <!-- 自定义对话框 -->
  <custom-dialog ref="customDialogRef" v-slot="{ formData }" :api-map="{ update: engineeringStageReUploadPicture}" header="*施工节点"
     @request-success="handleDialogRequestSuccess">
    <t-form-item label="附属图片" name="fileUrl"  :rules="[{ required: true, message: '请上传图片' }]">
      <upload v-model:files="formData.fileUrl" accept="image/*" theme="image"  multiple/>
    </t-form-item>
  </custom-dialog>

</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, inject, onMounted, Ref, ref, useTemplateRef } from 'vue';

import { engineeringStageListCRUD, engineeringStageReUploadPicture ,engineeringStagePictureExamine} from '@/api/project/details';
import { engineeringTeamCRUD } from '@/api/config/common-config';
import CustomArrayDialog from '@/components/custom/array-dialog/index.vue';
import CustomDialog from '@/components/custom/dialog/index.vue';
import Upload from '@/components/upload/index.vue';

import { useDictionaryStore, useUserStore, usePermissionStore } from '@/store';
import listToTree from '@/utils/listToTree';
import ImageViewer from '@/components/image-viewer/index.vue';
// 定义 props
const props = defineProps({
  injectKey: {
    type: String,
    default: 'engineeringDetails',
  },
});
// 用户仓库
const userStore = useUserStore();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 权限
const permissionStore = usePermissionStore();
// 加载状态
const loading = ref(false);
// 默认的注入键
const injectKey = props.injectKey
// 动态注入数据
const details = inject<Ref<Record<string, any>>>(injectKey);
// 施工详情
const engineeringDetails = details;
const engineeringId = details.value.engineeringId || details.value.id
const orderId = details.value.orderId || details.value.id
// 施工节点
const engineeringNodeTree = ref([])
// 获取施工节点列表
const handleGetengineeringStageList = () => {
  loading.value = true;
  const params = {
    pageSize: -1,
    engineeringId: engineeringId
  }
  engineeringStageListCRUD.page(params).then(data => {
    const tree = listToTree(data.list) 
    engineeringNodeTree.value = filterTreeWithImages(tree)
    console.log(engineeringNodeTree.value,'eng');
    

  }).catch(({ message }) => {
    MessagePlugin.error(message);
  }).finally(() => {
      loading.value = false;
    });
}
// 过滤树，只保留有图片的节点
const filterTreeWithImages = (tree: any[]) => {
  return tree
    .map((firstLevel) => {
      // 复制第一层节点
      const firstLevelCopy = { ...firstLevel };
      // 过滤第二层
      firstLevelCopy.children = firstLevel.children
        ?.map((secondLevel) => {
          // 复制第二层节点
          const secondLevelCopy = { ...secondLevel };
          // 过滤第三层
          secondLevelCopy.children = secondLevel.children?.filter((thirdLevel) => {
            return (
              thirdLevel.uploadStatus === '1' &&
              thirdLevel.fileUrl &&
              JSON.parse(thirdLevel.fileUrl).length > 0
            );
          });
          // 如果第三层有数据，则保留第二层
          return secondLevelCopy.children?.length > 0 ? secondLevelCopy : null;
        })
        .filter(Boolean);
      // 如果第二层有数据，则保留第一层
      return firstLevelCopy.children?.length > 0 ? firstLevelCopy : null;
    })
    .filter(Boolean);
};
// 检查是否存在需要审核的节点
const hasItemsNeedingApproval = (secondLevelItems: any[]) => {
  return secondLevelItems.some(secondLevel => {
    return secondLevel.children?.some((thirdLevel: any) => {
      return thirdLevel.imgApprovalStatus == 1 && 
             thirdLevel.uploadStatus === '1' && 
             thirdLevel.fileUrl && 
             JSON.parse(thirdLevel.fileUrl).length > 0;
    });
  });
};
onMounted(() => {
  handleGetengineeringStageList();

});
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'update') handleGetengineeringStageList();
};
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  console.log(params);
      const rawData = JSON.parse(JSON.stringify(params));
    console.log('处理后数据:', rawData); // 调试用
   const submitData: { id: any; engineeringId: any; result: any; }[] = [];
      const dataArray = Array.isArray(rawData) ? rawData : Object.values(rawData);
  // // Loop through each second level item
  dataArray.forEach((secondLevel: any) => {
    // Loop through each third level item
    secondLevel.children.forEach((thirdLevel: any) => {
      submitData.push({
        id: thirdLevel.id,
        engineeringId: engineeringId,
        result: thirdLevel.result
      });
    });
  });
  console.log(submitData,'su');
  // 从Proxy对象中获取原始值

  
  // return false
  return submitData;

};


// 自定义对话框ref
const customArrayDialogRef = useTemplateRef('customArrayDialogRef');
// 处理打开对话框
const handleOpenArrayDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  // 深拷贝参数避免修改原始数据
  const filteredParams = JSON.parse(JSON.stringify(params));
  
  // 过滤掉不需要审核的节点(imgApprovalStatus === 2)
  filteredParams.forEach((secondLevel: any) => {
    if (secondLevel.children) {
      secondLevel.children = secondLevel.children.filter((thirdLevel: any) => {
        return thirdLevel.imgApprovalStatus == 1 
      });
    }
  });
  
  // 只保留有需要审核子节点的二级节点
  const finalParams = filteredParams.filter((secondLevel: any) => {
    return secondLevel.children && secondLevel.children.length > 0;
  });

  customArrayDialogRef.value.open(mode, finalParams);
  // customArrayDialogRef.value.open(mode, params);
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  
  customDialogRef.value.open(mode, params);
};
// 根据审批状态获取标签样式以及文字
const getTagThemeAndLabel = (result: any) => {
  const map = [
    {
      theme: 'warning',
      label: '待审批',
    },
    {
      theme: 'success',
      label: '审批通过',
    },
    {
      theme: 'danger',
      label: '审批不通过',
    },
    {
      theme: 'danger',
      label: '审批已取消',
    },
  ];

  return result in map ? map[result] : { theme: 'default', label: '未知状态' };
};
</script>

<style lang="less" scoped>
.top-right {
  width: 100%;
  text-align: right;
  margin-bottom: 10px;
}

.header-right-content {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;

  .header-item {
    display: flex;
    align-items: center;
    white-space: nowrap;
    font-weight: normal;
    // flex: 1;

    .label {
      margin-right: 4px;
      // flex-shrink: 0;
    }

    .value {
      display: inline-flex;
      align-items: center;
      width: 70px;
      // flex: 1;
    }
  }
}

.flex {
  display: flex;
  align-items: center;
  font-weight: normal;
}
/* 让校验信息显示在右侧 */
:deep(.t-input__extra) {
  bottom: 6px !important;
  margin-left: 146px;
  max-width: 24%;
}
</style>